import 'dart:async';
import 'package:flutter/material.dart';
import 'package:ohosfloor/services/database_service.dart';
import 'entities/user_entity.dart';

class StreamUserPage extends StatefulWidget {
  const StreamUserPage({super.key});

  @override
  State<StreamUserPage> createState() => _StreamUserPageState();
}

class _StreamUserPageState extends State<StreamUserPage> {
  Timer? _updateTimer;
  bool _isUpdating = false;
  List<User> _topThreeUsers = [];

  @override
  void dispose() {
    _stopUpdating();
    super.dispose();
  }

  // 开始模拟数据更新
  void _startUpdating() async {
    if (_updateTimer != null && _updateTimer!.isActive) return;
    
    setState(() {
      _isUpdating = true;
    });
    
    // 只在开始时查询一次前三条数据
    await _initializeTopThreeUsers();
    
    _updateTimer = Timer.periodic(const Duration(milliseconds: 500), (timer) async {
      try {
        // 一次同时更新前三条数据
        final newUsers = _topThreeUsers.map(DatabaseService.instance.updateUserRandomly).toList();
        await DatabaseService.instance.updateUsers(newUsers);
      } catch (e) {
        print('更新用户数据时出错: $e');
      }
    });
    
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('开始模拟数据实时更新，每500ms更新一次前三条数据'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }
  
  // 初始化前三条用户数据
  Future<void> _initializeTopThreeUsers() async {
    try {
      final topThreeUsers = await DatabaseService.instance.getTopThreeUsers();
      if (mounted) {
        setState(() {
          _topThreeUsers = topThreeUsers;
        });
      }
    } catch (e) {
      print('初始化前三条用户数据时出错: $e');
    }
  }
  
  // 停止模拟数据更新
  void _stopUpdating() {
    _updateTimer?.cancel();
    _updateTimer = null;
    
    if (mounted) {
      setState(() {
        _isUpdating = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('已停止模拟数据更新'),
          duration: Duration(seconds: 2),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('实时数据观察'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Column(
        children: [
          // 顶部状态文案区域
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            margin: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: _isUpdating 
                  ? Colors.green.shade50 
                  : Colors.blue.shade50,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: _isUpdating 
                    ? Colors.green.shade200 
                    : Colors.blue.shade200,
                width: 1,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      _isUpdating ? Icons.visibility : Icons.visibility_off,
                      color: _isUpdating ? Colors.green : Colors.blue,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      _isUpdating ? '🔴 实时观察中' : '⚪ 静态观察',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: _isUpdating ? Colors.green.shade700 : Colors.blue.shade700,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  _isUpdating 
                      ? '正在每500ms自动更新前三条用户数据，观察实时变化效果'
                      : '点击右下角播放按钮开始模拟实时数据更新',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
          ),
          // 用户列表内容
          Expanded(child: _body()),
        ],
      ),
      floatingActionButton: FloatingActionButton.extended(
        heroTag: "toggle_update",
        onPressed: _isUpdating ? _stopUpdating : _startUpdating,
        backgroundColor: _isUpdating ? Colors.red : Colors.blue,
        icon: Icon(
          _isUpdating ? Icons.stop : Icons.play_arrow,
          color: Colors.white,
        ),
        label: Text(
          _isUpdating ? '停止更新' : '开始更新',
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Widget _body() {
    return StreamBuilder<List<User>>(
        stream: DatabaseService.instance.watchAllUsers(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }

          if (snapshot.hasError) {
            return Center(
              child: Text('错误: ${snapshot.error}'),
            );
          }

          final users = snapshot.data ?? [];

          if (users.isEmpty) {
            return const Center(
              child: Text(
                '暂无数据\n\n返回主页面插入一些示例数据',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16),
              ),
            );
          }

          return ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: users.length,
            itemBuilder: (context, index) {
              final user = users[index];
              return Card(
                margin: const EdgeInsets.only(bottom: 8),
                child: ListTile(
                  leading: CircleAvatar(
                    child: Text(user.id.toString()),
                  ),
                  title: Text(user.name),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('邮箱: ${user.email}'),
                      Text('年龄: ${user.age} | 部门: ${user.department}'),
                      Text('城市: ${user.city}, ${user.country}'),
                    ],
                  ),
                  trailing: Text(
                    '\$${user.salary}',
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.green,
                    ),
                  ),
                  isThreeLine: true,
                ),
              );
            },
          );
        },
      );
  }
}